package com.huangpuweb.task.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.huangpuweb.task.model.SysHpEmergencyEvent;
import com.huangpuweb.task.service.ApiService;
import com.huangpuweb.task.service.SyncSysDataService;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * 同步事件信息
 */
@Controller
public class SyncEmergencyEventDataJob {

    private static Logger logger = Logger.getLogger(SyncEmergencyEventDataJob.class);

    public static Double x_PI = 3.14159265358979324 * 3000.0 / 180.0;
    public static Double PI = 3.1415926535897932384626;
    public static Double a = 6378245.0;
    public static Double ee = 0.00669342162296594323;

    private SyncSysDataService syncSysDataService;

    @Autowired
    public void setSyncSysDataService(SyncSysDataService syncSysDataService) {
        this.syncSysDataService = syncSysDataService;
    }


    private ApiService apiService;

    @Autowired
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
    }


//    /**
//     * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
//     * 即 百度 转 谷歌、高德
//     *
//     * @param bd_lon
//     * @param bd_lat
//     * @returns {*[]}
//     */
//    public static void bd09togcj02(double bd_lon, double bd_lat) {
//
//        bd_lon = 121.475429;
//        bd_lat = 31.243478;
//        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
//        double x = bd_lon - 0.0065;
//        double y = bd_lat - 0.006;
//        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
//        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
//        double gg_lng = z * Math.cos(theta);
//        double gg_lat = z * Math.sin(theta);
//
//        double dlat = transformlat(gg_lng - 105.0, gg_lat - 35.0);
//        double dlng = transformlng(gg_lng - 105.0, gg_lat - 35.0);
//        double radlat = gg_lat / 180.0 * PI;
//        double magic = Math.sin(radlat);
//        magic = 1 - ee * magic * magic;
//        double sqrtmagic = Math.sqrt(magic);
//        dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
//        dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
//        double mglat = gg_lat + dlat;
//        double mglng = gg_lng + dlng;
//        System.out.println("mglat----"+mglat+"--mglng---"+mglng);
//    }
//
//    public static Double transformlat(double lng, double lat) {
//        Double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
//        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
//        ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
//        ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
//        return ret;
//    }
//
//
//    public static Double transformlng(double lng, double lat) {
//        Double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
//        ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
//        ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
//        ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
//        return ret;
//    }


    //判断点是否在面内
//    public static isInPolygon(checkPoint, polygonPoints) {
//
//    }
//    var counter = 0;
//    var i;
//    var xinters;
//    var p1, p2;
//    var pointCount = polygonPoints.length;
//    p1 = polygonPoints[0];
//
//    for (i = 1; i <= pointCount; i++) {
//        p2 = polygonPoints[i % pointCount];
//        if (checkPoint[0] > Math.min(p1[0], p2[0]) && checkPoint[0] <= Math.max(p1[0], p2[0])) {
//            if (checkPoint[1] <= Math.max(p1[1], p2[1])) {
//                if (p1[0] != p2[0]) {
//                    xinters = (checkPoint[0] - p1[0]) * (p2[1] - p1[1]) / (p2[0] - p1[0]) + p1[1];
//                    if (p1[1] == p2[1] || checkPoint[1] <= xinters) {
//                        counter++;
//                    }
//                }
//            }
//        }
//        p1 = p2;
//    }
//    if (counter % 2 == 0) {
//        return false;
//    } else {
//        return true;
//    }
//    }


    public void SyncEmergencyEventDataJobTask() throws Exception {
        // 创建HttpClient实例
        HttpClient client = HttpClientBuilder.create().build();
        LogFactory.getLog(this.getClass()).info("--------start-------SyncEmergencyEventDataJobTask----------" + new Date());
        //System.out.println("--------start-------SyncEmergencyEventDataJobTask----------");
        String starttime = syncSysDataService.getSysSettingByEmergencyEvent();
        int pagecount = 100;
        int pagesize = 0;
        int allcount = apiService.getListEmergencyEventAllCount(starttime);
        int pagelastsize = allcount % pagecount;
        if (pagelastsize > 0) {
            pagesize = (int) allcount / pagecount + 1;
        } else {
            pagesize = (int) allcount / pagecount;
        }
        JSONArray ja = new JSONArray();
        JSONObject jo = null;
        JSONObject jb = null;
        JSONObject locationjson = null;
        int id = 0;
        String eventType = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 1; i <= pagesize; i++) {
            List<SysHpEmergencyEvent> ListSysHpEmergencyEvent = apiService.getListSysHpEmergencyEvent(i, pagecount, starttime);
            for (SysHpEmergencyEvent sysHpEmergencyEvent : ListSysHpEmergencyEvent) {
//                System.out.println("sysHpEmergencyEventtime----"+sysHpEmergencyEvent.getEventTime());
                syncSysDataService.insertSysSettingByEmergencyEvent(sdf.format(sysHpEmergencyEvent.getStartTime()));
                try {
//                    // 根据URL创建HttpGet实例
//                    //http://172.82.4.1:8070
//                    //173.82.57.8:8070
//                    HttpGet get = new HttpGet("http://api.map.baidu.com/geocoder?address=" + sysHpEmergencyEvent.getAddress() + "&output=json&key=PyLa5E6K6BEGI0euwz1s9dWc&city=上海市");
//                    // 执行get请求，得到返回体
//                    HttpResponse response = client.execute(get);
//                    // 判断是否正常返回
//                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                        // 解析数据
//                        String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
//                        jo=JSONObject.parseObject(data);
//                        if(jo.get("status").equals("OK")){
//                            jb=jo.getJSONObject("result");
//                            locationjson = jb.getJSONObject("location");
//                            System.out.println(sysHpEmergencyEvent.getEventName() + "----" + locationjson.getString("lng") + "------" + locationjson.getString("lat"));
//                            sysHpEmergencyEvent.setBaiduLongitude(locationjson.getString("lng"));
//                            sysHpEmergencyEvent.setBaiduLatitude(locationjson.getString("lat"));

                    HttpGet get = new HttpGet("http://173.82.57.8:8070/geo-server/public/rest/geocoding/generalSearch?queryStr=上海市黄浦区" + sysHpEmergencyEvent.getAddress());
                    // 执行get请求，得到返回体
                    HttpResponse response = client.execute(get);
                    // 判断是否正常返回
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        // 解析数据
                        String data = EntityUtils.toString(response.getEntity(), Charsets.UTF_8);
                        ja = JSONArray.parseArray(data);
                        jo = ja.getJSONObject(0);
                        locationjson = jo.getJSONObject("location");
                        System.out.println(sysHpEmergencyEvent.getEventName() + "----" + locationjson.getString("x") + "------" + locationjson.getString("y"));
                        sysHpEmergencyEvent.setBaiduLongitude(locationjson.getString("x"));
                        sysHpEmergencyEvent.setBaiduLatitude(locationjson.getString("y"));
                        if (sysHpEmergencyEvent.getEventType().equals("290ef77a-7c02-41c1-a279-5e2ce0a45340")) {

                            eventType = "事故灾难";

                        } else if (sysHpEmergencyEvent.getEventType().equals("3d93e3d7-ba1d-4442-b825-44333b66290a")) {
                            eventType = "其他";
                            //1e1b5957-5818-4a0f-8f99-eb9ce46b3e51
                        } else if (sysHpEmergencyEvent.getEventType().equals("1e1b5957-5818-4a0f-8f99-eb9ce46b3e51")) {
                            eventType = "自然灾害";

                        } else if (sysHpEmergencyEvent.getEventType().equals("348be4c1-46ea-47c1-a0c8-2c7175a7a890")) {
                            eventType = "社会安全";

                        } else if (sysHpEmergencyEvent.getEventType().equals("2b80b610-461c-4389-bf61-49ba17b85f0d")) {
                            eventType = "公共卫生";

                        }

                        sysHpEmergencyEvent.setEventType(eventType);
                    }
                    syncSysDataService.insertSysHpEmergencyEvent(sysHpEmergencyEvent);

                } catch (Exception e) {
                    continue;
                }

            }
        }

        //System.out.println("--------end-------SyncEmergencyEventDataJobTask----------");
    }

    public static void main(String args[]) {
//        bd09togcj02(1,1);
    }
}
